package grammarbot

import de.danielnaber.languagetool.JLanguageTool
import de.danielnaber.languagetool.Language
import de.danielnaber.languagetool.rules.RuleMatch

import twitter4j.Status

class TweetChecker {
  def langTool = new JLanguageTool(Language.ENGLISH);

  TweetChecker() {
    langTool.activateDefaultPatternRules()
  }

  def getRuleMatches(String message) {
    langTool.check(message)
  }

  def check(Status status) {
    check(status.user.screenName, status.text)
  }

  def cleanText(String text) {
    // Prevent checker from saying you should capitalize URLs
    text.replace("http", "Http")
  }

  def extractSentenceRegion(String text, String replacement, int from, int to) {
    def start = Math.max(from - 10, 0)
    def end = Math.min(to + 10, text.length())
    
    (start > 0 ? "..." : "") + 
      text.substring(start, from) + 
      replacement + 
      text.substring(to, end) + 
      (end < text.length() ? "..." : "")
  }

  def hasText(String str) {
    return str && str.trim().length() > 0
  }

  def firstNonEmptyReplacement(RuleMatch ruleMatch) {
    def replacements = ruleMatch.suggestedReplacements
    def replacement = null
    if(replacements) {
      for(possibleReplacement in replacements) {
        if(hasText(possibleReplacement)) {
          replacement = possibleReplacement
          break;
        }
      }
    }
    replacement
  }

  def check(String user, String text) {
    def cleanedText = cleanText(text)    
    def ruleMatches = getRuleMatches(cleanedText)
    if(!ruleMatches.isEmpty()) {
      def ruleMatch = ruleMatches.get(0)
      def replacement = firstNonEmptyReplacement(ruleMatch)
      if(replacement) {
        def from = ruleMatch.fromPos
        def to = ruleMatch.toPos
        "@" + user + " did you mean \"" + extractSentenceRegion(text, replacement, from, to) + "\"?"
      } else if(hasText(ruleMatch.message)) {
        "@" + user + " I have detected a grammar error. ${ruleMatch.message}."
      }
    }
  }

}